import { Injectable } from '@angular/core';
import { RestService, Rest } from '@abp/ng.core';
import { Observable } from 'rxjs';
import { ConfigStateService } from '@abp/ng.core';
import { map, catchError, of } from 'rxjs';
import { delay } from 'rxjs/operators'; // Added for delay

export interface Location {
  locationId: string;
  locationName: string;
  capacity: number;
  supervisor: string;
  status: number;
  sortOrder: number;
  remarks: string;
  warehouseId?: string;
}

export interface Warehouse {
  id: string;
  warehouseCode: string;
  warehouseName: string;
  warehouseCapacity: number;
  warehouseAddress: string;
  managementDept: string;
  warehouseManager: string;
  locationCount: number;
  warehouseStatus: string;
  phone: string;
  sort: string | number;
  isLocked: boolean;
  remarks: string;
  creatorId?: string;
  creationTime?: string;
  locations?: Location[];
}

export interface WarehouseWithLocations {
  id: string;
  storehouse: Warehouse;
  locations: Location[];
  locationIdsToDelete?: string[];
}

export interface PagedResultDto<T> {
  items: T[];
  totalCount: number;
}

export interface DepartmentNode {
  id: string;
  name: string;
  children?: DepartmentNode[];
}

export interface WarehouseOperationLog {
  id: string;
  warehouseId: string;
  operationType: string;
  operatorId: string;
  operatorName?: string;
  operationTime: string;
  operationDescription?: string;
}

export interface WarehouseOperationLogResponse {
  items: WarehouseOperationLog[];
  totalCount: number;
}

@Injectable({
  providedIn: 'root'
})
export class StorehouseService {
  apiName = 'Default';

  constructor(
    private restService: RestService,
    private configState: ConfigStateService
  ) {}

  getList(params: any): Observable<PagedResultDto<Warehouse>> {
    // 构建查询参数，使用与后端API匹配的参数名
    const queryParams: any = {
      SkipCount: params.skipCount || 0,
      MaxResultCount: params.maxResultCount || 10,
      Sorting: params.sorting || undefined
    };

    // 添加过滤条件，使用与后端API匹配的参数名
    if (params.warehouseCode) {
      const searchValue = params.warehouseCode.trim();
      // 如果输入的是数字或字母，优先作为编号搜索
      if (/^[0-9a-zA-Z]+$/.test(searchValue)) {
        queryParams.WarehouseCode = searchValue;
      } else {
        // 否则作为名称搜索
        queryParams.WarehouseName = searchValue;
    }
    }

    // 高级查询参数处理
    if (params.warehouseName) {
      queryParams.WarehouseName = params.warehouseName;
    }
    if (params.minCapacity !== null && params.minCapacity !== undefined) {
      queryParams.MinCapacity = Number(params.minCapacity);
    }
    if (params.maxCapacity !== null && params.maxCapacity !== undefined) {
      queryParams.MaxCapacity = Number(params.maxCapacity);
    }
    if (params.managementDept) {
      queryParams.ManagementDept = params.managementDept;
    }
    if (params.warehouseManager) {
      queryParams.WarehouseManager = params.warehouseManager;
    }
    if (params.minLocationCount !== null && params.minLocationCount !== undefined) {
      queryParams.MinLocationCount = Number(params.minLocationCount);
    }
    if (params.maxLocationCount !== null && params.maxLocationCount !== undefined) {
      queryParams.MaxLocationCount = Number(params.maxLocationCount);
    }
    if (params.warehouseStatus) {
      queryParams.WarehouseStatus = params.warehouseStatus;
    }
    if (params.operator) {
      queryParams.Operator = params.operator;
    }
    if (params.operationTimeStart) {
      queryParams.OperationTimeStart = params.operationTimeStart;
    }
    if (params.operationTimeEnd) {
      queryParams.OperationTimeEnd = params.operationTimeEnd;
    }

    console.log('Query params:', queryParams);

    return this.restService.request<any, PagedResultDto<Warehouse>>({
      method: 'GET',
      url: '/api/app/storehouse/search',
      params: queryParams
    }, { apiName: this.apiName });
  }

  create(input: WarehouseWithLocations): Observable<Warehouse> {
    // 构建仓库基本信息
    const warehouse = {
      warehouseCode: input.storehouse.warehouseCode?.trim(),
      warehouseName: input.storehouse.warehouseName?.trim(),
      warehouseCapacity: Number(input.storehouse.warehouseCapacity) || 0,
      warehouseAddress: input.storehouse.warehouseAddress || '',
      managementDept: input.storehouse.managementDept || '',
      warehouseManager: input.storehouse.warehouseManager || '',
      phone: input.storehouse.phone || '',
      sort: input.storehouse.sort || '0',
      warehouseStatus: input.storehouse.warehouseStatus || '启用',
      remarks: input.storehouse.remarks || '',
      creatorId: this.getCurrentUser()
    };

    // 构建库位信息
    const locations = input.locations.map(location => ({
      locationId: location.locationId?.trim(),
      locationName: location.locationName?.trim(),
      capacity: Number(location.capacity) || 0,
      supervisor: location.supervisor || '',
      status: Number(location.status) || 0,
      sortOrder: Number(location.sortOrder) || 0,
      remarks: location.remarks || ''
    }));

    // 构建最终提交的数据
    const submitData = {
      storehouse: warehouse,
      locations: locations
    };

    console.log('Creating new warehouse with data:', submitData);

    return this.restService.request<any, Warehouse>({
      method: 'POST',
      url: '/api/app/storehouse/storehouse-with-locations',
      body: submitData
    }, { apiName: this.apiName });
  }

  update(id: string, input: WarehouseWithLocations): Observable<Warehouse> {
    console.log('StorehouseService.update - id:', id, 'input:', input);
    
    // 构建最终提交的数据
    const submitData = {
      id: id,
      storehouse: {
        warehouseCode: input.storehouse.warehouseCode?.trim(),
        warehouseName: input.storehouse.warehouseName?.trim(),
        warehouseCapacity: Number(input.storehouse.warehouseCapacity) || 0,
        warehouseAddress: input.storehouse.warehouseAddress || '',
        managementDept: input.storehouse.managementDept || '',
        warehouseManager: input.storehouse.warehouseManager || '',
        locationCount: Number(input.storehouse.locationCount) || 0,
        warehouseStatus: input.storehouse.warehouseStatus || '',
        phone: input.storehouse.phone || '',
        sort: Number(input.storehouse.sort) || 0,
        isLocked: Boolean(input.storehouse.isLocked),
        remarks: input.storehouse.remarks || ''
      },
      locations: input.locations.map(location => ({
        locationId: location.locationId?.trim(),
        locationName: location.locationName?.trim(),
        capacity: Number(location.capacity) || 0,
        supervisor: location.supervisor || '',
        status: Number(location.status) || 0,
        sortOrder: Number(location.sortOrder) || 0,
        remarks: location.remarks || '',
        warehouseId: id
      })),
      locationIdsToDelete: input.locationIdsToDelete || []
    };

    console.log('StorehouseService.update - submitData:', submitData);

    return this.restService.request<any, Warehouse>({
      method: 'PUT',
      url: '/api/app/storehouse/with-locations',
      body: submitData
    }, { apiName: this.apiName });
  }

  delete(id: string): Observable<void> {
    return this.restService.request<any, void>({
      method: 'DELETE',
      url: `/api/app/storehouse/${id}`
    }, { apiName: this.apiName });
  }

  enable(id: string): Observable<void> {
    return this.restService.request<any, void>({
      method: 'POST',
      url: `/api/app/storehouse/${id}/enable`
    }, { apiName: this.apiName });
  }

  disable(id: string): Observable<void> {
    return this.restService.request<any, void>({
      method: 'POST',
      url: `/api/app/storehouse/${id}/disable`
    }, { apiName: this.apiName });
  }

  lock(id: string): Observable<void> {
    return this.restService.request<any, void>({
      method: 'POST',
      url: `/api/app/storehouse/${id}/lock`
    }, { apiName: this.apiName });
  }

  getWarehouseNames(): Observable<{ items: string[] }> {
    return this.restService.request<any, { items: string[] }>({
      method: 'GET',
      url: '/api/app/storehouse/warehouse-names',
    }, { apiName: this.apiName });
  }

  // 获取单个仓库详情
  getById(id: string): Observable<any> {
    return this.restService.request<any, any>({
      method: 'GET',
      url: `/api/app/storehouse/${id}/storehouse-with-locations`,
    }, { apiName: this.apiName });
  }

  // 获取当前用户名称
  private getCurrentUser(): string {
    const currentUser = this.configState.getOne('currentUser');
    console.log('Current User:', currentUser);
    return currentUser?.userName || '';
  }

  // 修改仓库状态
  updateStatus(id: string, status: string): Observable<void> {
    return this.restService.request<any, void>({
      method: 'PUT',
      url: '/api/app/storehouse/status',
      body: {
        id: id,
        status: status || '启用'  // 确保 status 不为空
      },
      headers: {
        'Content-Type': 'application/json'
      }
    }, { apiName: this.apiName });
  }

  // 批量删除仓库
  batchDelete(ids: string[]): Observable<void> {
    if (!ids || ids.length === 0) {
      throw new Error('请先选择仓库');
    }
    return this.restService.request<any, void>({
      method: 'POST',
      url: '/api/app/storehouse/batch-delete',
      body: ids,
      headers: {
        'Content-Type': 'application/json'
      }
    }, { apiName: this.apiName });
  }

  // 获取仓库主管列表
  getWarehouseManagers(): Observable<string[]> {
    return this.restService.request<any, any>({
      method: 'GET',
      url: '/api/app/storehouse/warehouse-manager',
    }, { apiName: this.apiName }).pipe(
      map(response => {
        console.log('Warehouse managers response:', response);
        // 检查响应格式并相应处理
        if (Array.isArray(response)) {
          return response.map(item => {
            if (typeof item === 'string') {
              return item;
            }
            // 如果是对象，尝试获取name或displayName属性
            const obj = item as any;
            return obj.name || obj.displayName || obj.userName || obj.value || '';
          }).filter(name => name); // 过滤掉空字符串
        } else if (response && response.items) {
          return response.items.map(item => {
            if (typeof item === 'string') {
              return item;
            }
            const obj = item as any;
            return obj.name || obj.displayName || obj.userName || obj.value || '';
          }).filter(name => name);
        } else if (typeof response === 'object' && response) {
          // 如果是单个对象，尝试提取所有可能的名称属性
          return Object.values(response)
            .map(value => {
              if (typeof value === 'string') {
                return value;
              }
              if (typeof value === 'object' && value) {
                const obj = value as any;
                return obj.name || obj.displayName || obj.userName || obj.value || '';
              }
              return '';
            })
            .filter(name => name);
        }
        return [];
      }),
      catchError(error => {
        console.error('Failed to load warehouse managers:', error);
        return of([]);
      })
    );
  }

  // 获取部门树数据
  getDepartmentTree(): Observable<DepartmentNode[]> {
    return this.restService.request<any, DepartmentNode[]>({
      method: 'GET',
      url: '/api/app/storehouse/management-dept-tree',
    }, { apiName: this.apiName });
  }

  // 获取部门的子部门
  getDepartmentChildren(parentId: string): Observable<DepartmentNode[]> {
    return this.restService.request<any, DepartmentNode[]>({
      method: 'GET',
      url: '/api/app/storehouse/management-dept-children/' + parentId,
    }, { apiName: this.apiName });
  }

  // 获取操作记录列表
  getOperationLogs(params: any): Observable<WarehouseOperationLogResponse> {
    // 调用后端真实API
    return this.restService.request<any, WarehouseOperationLogResponse>({
      method: 'GET',
      url: '/api/app/warehouse-operation-log',
      params
    }, { apiName: this.apiName });
  }

  // 添加操作记录
  addOperationLog(log: Partial<WarehouseOperationLog>): Observable<any> {
    // 模拟后端API响应
    console.log('添加操作记录:', log);
    return of(true).pipe(delay(300));
  }
} 